package com.crm.aspect;

import com.crm.aonnation.AutoFill;
import com.crm.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @ClassName AutoFillAspect
 * @Description
 * @Author 19632
 * @Date 2024/10/11 11:23
 * @Version
 **/
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.crm.mapper..*.*(..))&&@annotation(com.crm.aonnation.AutoFill)")
    public void pointCut(){}

    @Before("pointCut()")
    public void autoFille(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();
        Object[] args = joinPoint.getArgs();
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        if(value==OperationType.INSERT){
            Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            setCreateTime.invoke(arg,now);
            setUpdateTime.invoke(arg,now);
        } else if (value == OperationType.UPDATE) {
            Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            setUpdateTime.invoke(arg,now);
        }
    }
}
